'''
Author: Deven
Email: liming@tuya.com
LastEditors: Please set LastEditors
FileName: &file name&
Description: 
Copyright: HANGZHOU TUYA INFORMATION TECHNOLOGY CO.,LTD
Company: http://www.tuya.com
Date: 2021-10-27 16:16:26
LastEditTime: 2021-11-03 19:14:19
'''
# coding:utf-8
import os
import sys
import json
import collections

#*****************************************************************#
# NOTE: This script is a compiled script. Please do not modify it #
#*****************************************************************#
# Pre Build processing.

# Parameter description：
# $1 - Application project name: tuyaos_zigbee_light_sample
# $2 - Application project version: 1.0.0
# python prebuild.py tuyaos_zigbee_light_sample 1.0.0

DESCRIPTION = ''
MANUFACTURE_ID = ''
IMAGE_TYPE = ''

MODEL_ID = ''
MANUFACTURE_NAME = ''

TUYA_PRODUCT_ID = ''
TUYA_CAPACITY = ''
APP_PRODUCT_TYPE = ''

MODULE_NAME = ''
DEV_ROLE = ''
CHIP_ID = ''


APP_PATH = sys.argv[1]
APP_NAME = sys.argv[2]
APP_VERSION = sys.argv[3]

CURR_PATH = os.getcwd()
TABLE_SPACE = 40
APP_PROJ_PATH = ''
JSON_CONFIG_NAME = 'appconfig.json'
JSON_CONFIG_PATH = os.path.join(APP_PROJ_PATH, JSON_CONFIG_NAME)
APP_SRC_PATH = os.path.join(APP_PROJ_PATH, 'src')
APP_INC_PATH = os.path.join(APP_PROJ_PATH, 'include')

# version info convert
def version_string_to_hex(version):
    str = version.replace('.', '')
    strlen = len(str)
    version_hex = ((int(str[0:1]) << 6) & 0xc0) + ((int(str[1:2]) << 4) & 0x30)
    if (strlen > 3):
        version_hex = version_hex + (int(str[2:4]) & 0x0f)
    else:
        version_hex = version_hex + (int(str[2:3]) & 0x0f)
    # print(hex(version_hex))
    return version_hex

# firmware info parser
def firmware_info_get():
    global DESCRIPTION
    global MANUFACTURE_ID
    global IMAGE_TYPE

    global MODEL_ID
    global MANUFACTURE_NAME

    global TUYA_PRODUCT_ID
    global TUYA_CAPACITY
    global TUYA_PRODUCT_TYPE

    global MODULE_NAME
    global DEV_ROLE
    global CHIP_ID

    print("firmware information parse start...")
    file = open(JSON_CONFIG_PATH, 'rb')
    fileJson = json.load(file, object_pairs_hook=collections.OrderedDict)

    DESCRIPTION = fileJson['firmwareInfo']['description']
    MANUFACTURE_ID = fileJson['firmwareInfo']['manufacture_id']
    IMAGE_TYPE = fileJson['firmwareInfo']['image_type']

    MODEL_ID = fileJson['firmwareInfo']['model_id']
    MANUFACTURE_NAME = fileJson['firmwareInfo']['manufacture_name']

    try:
        TUYA_PRODUCT_ID = fileJson['firmwareInfo']['tuya_product_id']
    except Exception as e:
        try:
            TUYA_PRODUCT_ID = fileJson['firmwareInfo']['pid']
        except Exception as e:
            print("json parse fail !!! need define tuya_product_id or pid")

    try:
        TUYA_CAPACITY = fileJson['firmwareInfo']['tuya_capacity']
    except Exception as e:
        TUYA_CAPACITY = fileJson['firmwareInfo']['manufacture_name']
        MANUFACTURE_NAME = fileJson['firmwareInfo']['manufacture_name']+fileJson['firmwareInfo']['pid']

    try:
        TUYA_PRODUCT_TYPE = fileJson['firmwareInfo']['tuya_product_type']
    except Exception as e:
        TUYA_PRODUCT_TYPE = MODEL_ID

    MODULE_NAME = fileJson['firmwareInfo']['module_name']
    DEV_ROLE = fileJson['firmwareInfo']['dev_role']
    CHIP_ID = fileJson['firmwareInfo']['chip_id']


    file.close()
    print("firmware information parse success")

# write ifno to generate file
def ato_generate_file_header():
    def wrapper(func):
        def __wrapper(*args,**kwargs):
            print("file generate start...")
            fileObject = open(args[0], 'w')
            fileObject.writelines(
                "/*************************************************************************************/" + '\n')
            fileObject.writelines("/* Automatically-generated file. Do not edit! */" + '\n')
            fileObject.writelines(
                "/*************************************************************************************/" + '\n\n')
            fileObject.close()
            return func(*args,**kwargs)
        return __wrapper
    return wrapper


# generat firmware function in config.c
def generate_firmware_func_config_c(fileObj):

    fileObj.writelines("#include \"app_config.h\"" + '\n')
    fileObj.writelines("#include \"tuya_iot_config.h\"" + '\n')
    fileObj.writelines("#include \"tal_firmware_cfg.h\"" + '\n\n\n')

    # generate app info config function
    fileObj.writelines("OPERATE_RET tuya_app_firmware_config(VOID_T)" + '\n')
    fileObj.writelines("{" + '\n')
    
    fileObj.writelines("    TAL_FW_INIT_T fw_init = {" + '\n')
    fileObj.writelines("        .name = APP_FIRMWARE_NAME," + '\n')
    fileObj.writelines("        .model_id = APP_MODEL_ID," + '\n')
    fileObj.writelines("        .manu_name = APP_MANUFACTURE_NAME," + '\n')
    fileObj.writelines("        .capacity = APP_CAPACITY," + '\n')
    fileObj.writelines("        .product_id = APP_PRODUCT_ID," + '\n')
    fileObj.writelines("        .product_type = APP_PRODUCT_TYPE," + '\n')
    fileObj.writelines("        .fw_version = APP_FIRMWARE_VER," + '\n') 
    fileObj.writelines("        .manu_id = APP_MANUFACTURE_ID," + '\n') 
    fileObj.writelines("        .image_type = APP_IMAGE_TYPE," + '\n')   
    fileObj.writelines("    };" + '\n')
    fileObj.writelines("    return tal_firmware_info_init(&fw_init);" + '\n')

    fileObj.writelines("}" + '\n\n\n')

    # generate sdk info config function
    fileObj.writelines("OPERATE_RET tuya_sdk_information_config(VOID_T)" + '\n')
    fileObj.writelines("{" + '\n')
    
    fileObj.writelines("    CHAR_T *sdk_ver = IOT_SDK_VER;" + '\n')
    fileObj.writelines("    CHAR_T *kcfg_ver = \"0.0.0\";" + '\n')
    fileObj.writelines("    CHAR_T *kernel_ver = KERNEL_VERSION;" + '\n')
    fileObj.writelines("    return tal_tuyaos_info_init(sdk_ver, kcfg_ver, kernel_ver);" + '\n')

    fileObj.writelines("}" + '\n\n\n')



# generate config.c file
@ato_generate_file_header()
def ato_generat_sdk_information_c(*args, **kwargs):
    fileObject = open(args[0], 'a+')

    # add func c
    generate_firmware_func_config_c(fileObject)

    fileObject.close()
    print(args[0]+"config file write success")


# generate fimware config
def generate_fimware_macro_config_h(fileObj):

    fileObj.writelines("#define APP_FIRMWARE_NAME".ljust(TABLE_SPACE) + '\"' + APP_NAME + '\"' + '\n')
    fileObj.writelines("#define APP_FIRMWARE_VER".ljust(TABLE_SPACE) + hex(version_string_to_hex(APP_VERSION)) + '\n')
    fileObj.writelines("#define APP_MANUFACTURE_ID".ljust(TABLE_SPACE) + MANUFACTURE_ID + '\n')
    fileObj.writelines("#define APP_IMAGE_TYPE".ljust(TABLE_SPACE) + IMAGE_TYPE + '\n')
    fileObj.writelines("#define APP_MODEL_ID".ljust(TABLE_SPACE) + '\"' + MODEL_ID + '\"' + '\n')
    fileObj.writelines("#define APP_MANUFACTURE_NAME".ljust(TABLE_SPACE) + '\"' + MANUFACTURE_NAME + '\"' + '\n')

    fileObj.writelines("#define APP_PRODUCT_ID".ljust(TABLE_SPACE) + '\"' + TUYA_PRODUCT_ID + '\"' + '\n')
    fileObj.writelines("#define APP_CAPACITY".ljust(TABLE_SPACE) + '\"' + TUYA_CAPACITY + '\"' + '\n')
    fileObj.writelines("#define APP_PRODUCT_TYPE".ljust(TABLE_SPACE) + '\"' + TUYA_PRODUCT_TYPE + '\"' + '\n')

    fileObj.writelines("#define APP_MODULE_NAME".ljust(TABLE_SPACE) + '\"' + MODULE_NAME + '\"' + '\n')
    fileObj.writelines("#define APP_DEV_ROLE".ljust(TABLE_SPACE) + '\"' + DEV_ROLE + '\"' + '\n')
    fileObj.writelines("#define APP_CHIP_ID".ljust(TABLE_SPACE) + '\"' + CHIP_ID + '\"' + '\n\n\n')


# generate config.h file
@ato_generate_file_header()
def ato_generate_config_h(*args, **kwargs):

    fileObject = open(args[0], 'a+')

    fileObject.writelines("#ifndef __APP_CONFIG_H__" + '\n')
    fileObject.writelines("#define __APP_CONFIG_H__" + '\n\n')
    fileObject.writelines("/* automatically generated app firmware information! */" + '\n')

    # add macro
    generate_fimware_macro_config_h(fileObject)

    fileObject.writelines('\n' + "#endif" + '\n')
    fileObject.close()
    print(args[0]+"config file write success")


# if __name__ == "__main__":
#     os.chdir('../../'+APP_PATH)
#     firmware_info_get()
#     inc_path = os.path.join(APP_INC_PATH, 'app_config.h')
#     src_path = os.path.join(APP_SRC_PATH, 'app_config.c')
#     ato_generate_config_h(inc_path)
#     ato_generat_sdk_information_c(src_path)
#     os.chdir(CURR_PATH)

class Pre_build():
    def __init__(self):
        os.chdir('../../'+APP_PATH)
        firmware_info_get()
        inc_path = os.path.join(APP_INC_PATH, 'app_config.h')
        src_path = os.path.join(APP_SRC_PATH, 'app_config.c')
        ato_generate_config_h(inc_path)
        ato_generat_sdk_information_c(src_path)
        os.chdir(CURR_PATH)


